const request = require('request');
const { userAgentList } = require('../config');
const querystring = require('querystring');
const encrypt = require('./crypto');
const randomUserAgent = () => userAgentList[Math.floor(Math.random() * userAgentList.length)];
let getNeteaseCloudOptions = url => {
	return {
		url: `http://music.163.com${url}`,
		method: 'GET',
		headers: {
			Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
			'Accept-Encoding': 'gzip,deflate',
			'Accept-Language': 'zh-CN,zh;q=0.9',
			Host: 'music.163.com',
			Connection: 'keep-alive',
			Origin: 'http://music.163.com/',
			Referer: 'http://music.163.com/',
			'Content-Type': 'application/json',
			'Upgrade-Insecure-Requests': 1,
			'User-Agent': randomUserAgent()
		},
		gzip: true
	}; //
};
let postNeteaseCloudOptions = (url, data, isEncrypt) => {
	let baseOption = {
		url: `http://music.163.com${url}`,
		method: 'POST',
		headers: {
			Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
			'Accept-Encoding': 'gzip,deflate',
			'Accept-Language': 'zh-CN,zh;q=0.9',
			Connection: 'keep-alive',
			Host: 'music.163.com',
			Origin: 'http://music.163.com/',
			Referer: 'http://music.163.com/',
			'Content-Type': 'application/json',
			'Upgrade-Insecure-Requests': 1,
			'User-Agent': randomUserAgent()
		}
	};
	if (isEncrypt) {
		const cryptoreq = Encrypt(data);
		baseOption.body = querystring.stringify({
			params: cryptoreq.params,
			encSecKey: cryptoreq.encSecKey
		});
	} else {
		baseOption.body = data;
	}
	return baseOption;
};
const getNetClound = ({ url }) => {
	return new Promise((resolve, reject) => {
		request(getNeteaseCloudOptions(url), (error, response, body) => {
			if (error) return reject(error);
			return resolve(body);
		});
	});
};
const postNetClound = ({ url, data, isEncrypt }) => {
	return new Promise((resolve, reject) => {
		request(postNeteaseCloudOptions(url, data, isEncrypt), (error, response, body) => {
			if (error) return reject(error);
			return resolve(body);
		});
	});
};
module.exports = { getNetClound, postNetClound };
